#include "cxiheaderview.h"
#include "cxiverticalheaderview.h"
#include "common/logger/logger.h"

#include <QHeaderView>
#include <QScrollBar>
#include <QTimer>
#include <private/table/cxiadvancedview.h>
#include <private/table/delegate/globaldelegaterouter.h>
#include <private/table/delegate/columndelegaterouter.h>
#include <private/table/delegate/styleditemdelegatefactory.h>
#include <private/table/cxiheaderview.h>

CxiAdvancedView::CxiAdvancedView(QWidget* parent)
	: QTreeView(parent), m_verticalHeader(nullptr), m_cornerButton(nullptr)
	  , m_globalRouter(new GlobalDelegateRouter(this))
{
	auto header = new CxiHeaderView(Qt::Horizontal, this);
	setHeader(header);
	StyledItemDelegateFactory::init(nullptr);
	this->setItemDelegate(m_globalRouter);
	m_verticalHeader = new CxiVerticalHeaderView(this);
	m_verticalHeader->show();
	m_verticalHeader->setView(this);
	m_verticalHeader->show();

	// 连接：滚动刷新
	connect(verticalScrollBar(), &QScrollBar::valueChanged, m_verticalHeader, [this](int) { m_verticalHeader->update(); });

	// 展开 / 折叠 刷新
	connect(this, &QTreeView::expanded, m_verticalHeader, [this](const QModelIndex&) { m_verticalHeader->update(); });
	connect(this, &QTreeView::collapsed, m_verticalHeader, [this](const QModelIndex&) { m_verticalHeader->update(); });

	// 模型结构变化刷新
	if (model())
	{
		connect(model(), &QAbstractItemModel::rowsInserted, m_verticalHeader, [this]() { m_verticalHeader->update(); });
		connect(model(), &QAbstractItemModel::rowsRemoved, m_verticalHeader, [this]() { m_verticalHeader->update(); });
		connect(model(), &QAbstractItemModel::modelReset, m_verticalHeader, [this]() { m_verticalHeader->update(); });
	}

	m_cornerButton = new QToolButton(this);
	m_cornerButton->setAutoRaise(true);
	m_cornerButton->setText("≡");
	m_cornerButton->show();

	connect(m_cornerButton, &QToolButton::clicked, this, [this]() {
		emit connerButtonClicked();
	});

	connect(m_verticalHeader, &QHeaderView::sectionResized, this, &CxiAdvancedView::updateCornerGeometry);
	connect(m_verticalHeader, &QHeaderView::sectionMoved, this, &CxiAdvancedView::updateCornerGeometry);

	// 延迟更新布局
	// QTimer::singleShot(0, this, [this]() {
	// 	updateHeaderMargins();
	// 	updateCornerGeometry();
	// });
}


CxiAdvancedView::~CxiAdvancedView()
{
}


void CxiAdvancedView::setVerticalHeader(CxiVerticalHeaderView* header)
{
	if (!header) return;
	if (m_verticalHeader) m_verticalHeader->deleteLater();
	m_verticalHeader = header;
	m_verticalHeader->setParent(this);
	connect(m_verticalHeader, &QHeaderView::sectionResized, this, &CxiAdvancedView::updateCornerGeometry);
	connect(m_verticalHeader, &QHeaderView::sectionMoved, this, &CxiAdvancedView::updateCornerGeometry);
	updateHeaderMargins();
}

void CxiAdvancedView::resizeEvent(QResizeEvent* event)
{
	QTreeView::resizeEvent(event);
	updateHeaderMargins();
	updateCornerGeometry();
}

void CxiAdvancedView::scrollContentsBy(int dx, int dy)
{
	QTreeView::scrollContentsBy(dx, dy);
	if (m_verticalHeader && m_verticalHeader->isVisible())
	{
	}
}


void CxiAdvancedView::setConerButtonEnabled(bool enabled)
{
}

void CxiAdvancedView::setConerButtonIcon(QIcon icon)
{
}

void CxiAdvancedView::updateGeometries()
{
	QTreeView::updateGeometries();
	updateHeaderMargins();
	updateCornerGeometry();
	if (m_verticalHeader) m_verticalHeader->update();
}

void CxiAdvancedView::updateHeaderMargins()
{
	int left = (m_verticalHeader && m_verticalHeader->isVisible()) ? m_verticalHeader->width() : 0;
	int top = (header() && header()->isVisible()) ? header()->height() : 0;
	// 为数据视图预留空间
	setViewportMargins(left, top, 0, 0);

	if (header())
	{
		header()->setParent(this);
		header()->move(left, 0);
		header()->raise();
	}
	if (m_verticalHeader)
	{
		m_verticalHeader->setParent(this);
		m_verticalHeader->move(0, top);
		m_verticalHeader->raise();
	}
	if (m_verticalHeader) m_verticalHeader->update();

}

void CxiAdvancedView::updateCornerGeometry()
{
	int left = (m_verticalHeader && m_verticalHeader->isVisible()) ? m_verticalHeader->width() : 0;
	int top = (header() && header()->isVisible()) ? header()->height() : 0;
	if (m_cornerButton)
	{
		m_cornerButton->setVisible(left > 0 && top > 0);
		m_cornerButton->setGeometry(0, 0, left, top);
		m_cornerButton->raise();
	}
	if (header()) header()->setGeometry(left, 0, qMax(0, viewport()->width()), top);
	if (m_verticalHeader) m_verticalHeader->setGeometry(0, top, left, qMax(0, viewport()->height()));
}

QRect CxiAdvancedView::visualRect(const QModelIndex& index) const
{
	QRect r = QTreeView::visualRect(index);
	if (!r.isValid() || !m_verticalHeader || !m_verticalHeader->isVisible()) return r;
	// r.translate(-m_verticalHeader->width(), 0);
	// LOG_INFO(index.row(), "-",index.column());
	return r;
}

QModelIndex CxiAdvancedView::indexAt(const QPoint& p) const
{
	QPoint pt = p;
	// if (m_verticalHeader && m_verticalHeader->isVisible()) pt.setX(p.x() - m_verticalHeader->width());

	LOG_INFO(p.x(), ",", p.y());
	return QTreeView::indexAt(pt);
}


void CxiAdvancedView::applyColumnConfig(const QList<cxitable::GridColumnConfig>& columns)
{
	auto* header = dynamic_cast<CxiHeaderView*>(this->header());
	if (!header) return;
	for (int col = 0; col < columns.size(); ++col)
	{
		const cxitable::GridColumnConfig& gc = columns[col];

		// 根据列样式设置委托
		auto columnRouter = new ColumnDelegateRouter(m_globalRouter);
		QAbstractItemDelegate* delegate = StyledItemDelegateFactory::createDelegate(gc, columnRouter);
		columnRouter->setDefaultDelegate(dynamic_cast<QStyledItemDelegate*>(delegate));
		m_globalRouter->setColumnRouter(gc.visibleIndex, columnRouter);

		if (!gc.visible)
		{
			this->setColumnHidden(col, true);
			continue;
		}
		this->setColumnWidth(col, gc.width);//设置宽度
		if (gc.autoWidth) header->setSectionResizeMode(col, QHeaderView::ResizeToContents);//自适应宽度

		if (gc.headForeColor.isValid())
		{
			//列头前景色
			header->setForeColor(col, gc.headForeColor);
		}

		if (gc.headBackColor.isValid())
		{
			//列头背景色
			header->setBackColor(col, gc.headBackColor);
		}

		//设置文本对齐方式
		if (gc.textAlignment != 0)
		{
			model()->setHeaderData(col, Qt::Horizontal, static_cast<int>(gc.textAlignment), Qt::TextAlignmentRole);
		}

	}
}

void CxiAdvancedView::setCellDelegate(int row, int column, QStyledItemDelegate* delegate) const
{
	m_globalRouter->setCellDelegate(row, column, delegate);
}

void CxiAdvancedView::setCellDelegate(int row, int column, const cxitable::GridColumnConfig& config) const
{
	QAbstractItemDelegate* delegate = StyledItemDelegateFactory::createDelegate(config, m_globalRouter->columnRouter(config.visibleIndex));
	setCellDelegate(row, column, dynamic_cast<QStyledItemDelegate*>(delegate));
}

QHeaderView* CxiAdvancedView::verticalHeader() const
{
	return m_verticalHeader;
}